/*
 * Database Management class 
 *
 */
 SocioMusicDBManager  = function() {
 	var dbSize = 4*1024*1024;
 	this.db    = openDatabase("SocioMusicDB","1.0","sociomusic db",dbSize);
 	this.createTables();
 }

 SocioMusicDBManager.prototype.createTables = function() {
 	self = this.db;
 	self.transaction(function(tx){
 		console.log('creating the table "File"');
 		tx.executeSql('CREATE TABLE IF NOT EXISTS files(ID INTEGER PRIMARY KEY ASC, parentFolder TEXT, name TEXT, size TEXT UNIQUE, url TEXT, type TEXT, mainTagId INTEGER ) ',[]);
 	});
 	self.transaction(function(tx){
 		console.log('creating the table "tags"');
 		tx.executeSql('CREATE TABLE IF NOT EXISTS tags(ID INTEGER PRIMARY KEY ASC, rating INTEGER, name TEXT UNIQUE,count INTEGER) ',[]);
 	});
 	self.transaction(function(tx){
 		console.log('creating the table "userTags"');
 		tx.executeSql('CREATE TABLE IF NOT EXISTS userTags(ID INTEGER PRIMARY KEY ASC, song INTEGER, tag INTEGER) ',[]);
 	});

  self.transaction(function(tx){
    console.log('creating the urls');
    tx.executeSql('UPDATE files SET url= " "' ,[]);
  });
 };

 SocioMusicDBManager.prototype.addObject = function(tableName, obj, successFunc, errorFunc){
 	var keys     = getKeys(obj);
 	var queryStr = 'INSERT INTO '+tableName+ '('+keys.join(',')+') VALUES ('+Array(keys.length+1).join('?').split('').join(',')+')';
 	var values   = getValues(obj);

 	var self     = this.db;
 	self.transaction(function(tx){
 		tx.executeSql(queryStr,values,successFunc,errorFunc);
 	});	
 }

 SocioMusicDBManager.prototype.updateObject = function(tableName, criteria, obj, successFunc, errorFunc){
 	var vals     = [];
 	var queryStr = 'UPDATE '+ tableName + ' SET ';
 	addValues(obj, queryStr, vals);
 	queryStr    += ' WHERE ';
 	addValues(criteria, queryStr, vals);

 	var self     = this.db;
 	self.transaction(function(tx){
 		tx.executeSql(queryStr,vals,successFunc,errorFunc);
 	});	

 	function addValues(objt){
 		var keys = getKeys(objt);
 		var str  = ' ';
 		for (var i = 0; i < keys.length; i++) {
 			str += keys[i] + ' = ?, ';
 			vals.push(objt[keys[i]]);
 		};
 		str      = str.replace(/, $/,'');
 		queryStr += str;
 	}
 }

SocioMusicDBManager.prototype.getFiles = function(_successFunc) {
  var queryStr = 'SELECT * FROM files where url is not " "';
  self.transaction(function(tx){
    tx.executeSql(queryStr,[],_successFunc,function(){});
  });
};

/**
  * @return a rows object . row.length gives size and row.item(index) gives the object
  */
  SocioMusicDBManager.prototype.getObjects = function(_tableName, _cols, _criteria, _successFunc, _errorFunc){
  	var vals     = [];
  	var queryStr = 'SELECT ';
  	queryStr += getCols();
  	queryStr += ' FROM '+ _tableName;
  	getCriteria(_criteria);  

  	var self     = this.db;
  	self.transaction(function(tx){
  		tx.executeSql(
  			queryStr,
  			vals,
  			function(tx,rs){
  				_successFunc(tx,rs);
  			},
  			_errorFunc
  			);
  	});	

  	function getCols(){
  		var colsList= '';
  		if(_cols.length > 0){
  			var str = ' ';
  			for (var i = 0; i < _cols.length; i++) {
  				str += _cols[i] + ', ';
  			};
  			str      = str.replace(/, $/,'');
  			colsList = str;
  		}else{
  			colsList = '* ';
  		}
  		return colsList;
  	}
  	function getCriteria(objt){
  		var keys  = getKeys(objt);
  		if(keys.length > 0){
  			var str = ' WHERE ';
  			for (var i = 0; i < keys.length; i++) {
  				str += keys[i] + ' = ?, ';
  				vals.push(objt[keys[i]]);
  			};
  			str = str.replace(/, $/,'');
  			queryStr += str;
  		}
  	}
  }

  var getKeys = function(obj){
  	var keys = [];
  	for(var key in obj){
  		if (obj.hasOwnProperty(key)) {
  			keys.push(key);
  		}
  	}
  	return keys;
  }
  var getValues = function(obj){
  	var keys   = getKeys(obj);
  	var values = [];
  	for (var i = 0; i < keys.length; i++) {
  		values.push(obj[keys[i]]);
  	};
  	return values;
  }

